package com.love.marriage.cloud.service.impl;

import com.love.marriage.cloud.service.VirtualNumberService;
import com.love.marriage.common.redisKey.VirtualNumberKey;
import com.love.marriage.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@RequiredArgsConstructor
@Slf4j
public class VirtualNumberServiceImpl implements VirtualNumberService {

    private final RedisUtils redisUtils;

    public String getExistingBinding(String phoneA, String phoneB) {
        Set<String> binds = redisUtils.keys(VirtualNumberKey.virtualNumberBindingKey);
        for (String key : binds) {
            String existingPhoneA = redisUtils.hget(key, "phoneA");
            String existingPhoneB = redisUtils.hget(key, "phoneB");
            if ((existingPhoneA != null && existingPhoneA.equals(phoneA)) ||
                    (existingPhoneB != null && existingPhoneB.equals(phoneB))) {
                return key.replace(VirtualNumberKey.virtualNumberBindingKey.getPrefix(), "");
            }
        }
        return null;
    }

    public String bindVirtualNumber(String phoneA, String phoneB) {
        // 首先检查是否已有绑定的虚拟号码
        String existingVirtualNumber = getExistingBinding(phoneA, phoneB);
        if (existingVirtualNumber != null) {
            return existingVirtualNumber;  // 如果已经绑定过，直接返回
        }

        // 获取一个未绑定的虚拟号码
        String virtualNumber = redisUtils.spop(VirtualNumberKey.virtualNumberKey);
        if (virtualNumber == null) {
            // 如果池中没有未绑定的号码，选择解绑
            virtualNumber = unbindOldestBinding();
        }

        // 绑定虚拟号码到 phoneA 和 phoneB
        redisUtils.hset(VirtualNumberKey.virtualNumberBindingKey, virtualNumber, "phoneA", phoneA);
        redisUtils.hset(VirtualNumberKey.virtualNumberBindingKey, virtualNumber, "phoneB", phoneB);

        System.out.println("绑定成功：phoneA=" + phoneA + ", phoneB=" + phoneB + ", virtualNumber=" + virtualNumber);
        return virtualNumber;
    }

    private String unbindOldestBinding() {
        Set<String> keys = redisUtils.keys(VirtualNumberKey.virtualNumberBindingKey);
        for (String key : keys) {
            String virtualNumber = key.replace(VirtualNumberKey.virtualNumberBindingKey.getPrefix(), "");
            redisUtils.delete(key);  // 删除绑定关系
            redisUtils.sadd(VirtualNumberKey.virtualNumberKey, virtualNumber); // 将虚拟号码重新加入未绑定池
            System.out.println("解绑成功：virtualNumber=" + virtualNumber);
            return virtualNumber;
        }
        return null;
    }

    // 初始化虚拟号码池
    @Override
    public Boolean initVirtualNumberPool(String... virtualNumbers) {
        redisUtils.sadd(VirtualNumberKey.virtualNumberKey, virtualNumbers);  // 初始化未绑定虚拟号码池
        System.out.println("虚拟号码池已初始化");
        return true;
    }
}
